<template>
  <div id="box">
    <el-card v-loading="tableLoading" shadow="never" :class="{pointerEvents:tableLoading}">
      <div>
        <el-form ref="queryForm" :inline="true" :model="queryData" class="demo-form-inline">
          <el-form-item label="时间范围" prop="queryDate">
            <el-date-picker
              v-model="queryData.queryDate"
              type="monthrange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              value-format="yyyy-MM"
              :clearable="false"
            />
          </el-form-item>
          <el-form-item label="统计质控" prop="querytype">
            <el-select v-model="queryData.querytype" placeholder="统计质控" clearable>
              <el-option v-for="(item,index) in optionData" :key="index" :label="item" :value="index" />
            </el-select>
          </el-form-item>
          <el-form-item class="fr">
            <el-button type="primary" @click="queryEchart()">查询</el-button>
            <el-button @click="resetForm('queryForm')">重置</el-button>
          </el-form-item>
          <el-divider class="dividerLine" />
        </el-form>
      </div>
      <div>
        <el-row>
          <el-col v-show="pie_or_line=='pie'" :span="10">
            <div ref="chart" class="echarts-dom" />
          </el-col>
          <el-col v-show="pie_or_line=='line'" :span="24">
            <div ref="chartLine" class="echarts-dom" />
          </el-col>
          <el-col v-if="monthTableData.length>0" :span="tableCol">
            <el-table :data="monthTableData" style="width: 100%" border size="mini" height="500">
              <!-- <el-table-column type="selection" width="55" align="center" /> -->
              <el-table-column type="index" width="50" align="center">
                <template slot-scope="scope" align="center">
                  {{ scope.$index+1 }}
                </template>
              </el-table-column>
              <el-table-column prop="month" label="月份" align="center" />
              <el-table-column prop="summonth" label="数量" align="center" />
              <el-table-column fixed="right" label="操作" width="150" align="center">
                <template slot-scope="scope">
                  <el-button size="mini" class="mr-10" type="text" @click="monthDetails(scope.row)">查看详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col v-if="tableData.length>0" :span="24" style="margin-top: 20px;">
            <el-table v-loading="tableLoading" :data="tableData" style="width: 100%" border size="mini">
              <!-- <el-table-column type="selection" width="55" align="center" /> -->
              <el-table-column type="index" width="50" align="center">
                <template slot-scope="scope" align="center">
                  {{ (pageNum - 1) * pageSize + scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="firstMedicalContactDateTime" label="首次医疗接触" align="center" />
              <el-table-column prop="patientId" label="患者编号" align="center" />
              <el-table-column prop="name" label="患者姓名" align="center" />
              <el-table-column prop="sex" label="性别" align="center" width="55" />
              <el-table-column prop="age" label="年龄" align="center" width="55" />
              <el-table-column prop="diagnoseContent" label="初步诊断" align="center" />

              <el-table-column fixed="right" label="操作" width="150" align="center">
                <template slot-scope="scope">
                  <el-button size="mini" class="mr-10" type="text" @click="jumpsee(scope.row)">跳转查看</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              class="pagination"
              :current-page.sync="pageNum"
              :page-sizes="[10, 20]"
              :page-size.sync="pageSize"
              layout="sizes, prev, pager, next ,total"
              :total="count"
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-col>
        </el-row>
      </div>
      </el-col>
      </el-row>
    </el-card></div>
  </el-card>
  </div>
</template>

<script>
import echarts from 'echarts'
import { statisticsQuery, statisticsQueryMonth, statisticsQueryInfo } from '@/api/statistical/statistical-analysis'
export default {
  data() {
    return {
      queryData: {
        queryDate: [
          new Date(new Date().getFullYear() - 1, (new Date().getMonth())),
          new Date(new Date().getFullYear(), (new Date().getMonth()))
        ],
        querytype: 'stroke1'
      },
      pageSize: 10,
      pageNum: 1,
      count: 0,
      pie_or_line: 'pie',
      tableCol: 24,
      tableData: [],
      monthTableData: [],
      tableLoading: false,
      optionData: {
        stroke1: '脑卒中患者医保病人比例',
        stroke2: '脑卒中患者平均住院日'
      },

      pieDataName: {
        medical1: '城镇职工基本医疗保险',
        medical2: '城镇居民基本医疗保险',
        medical3: '新型农村合作医疗',
        medical4: '商业医疗保险',
        medical5: '全公费',
        medical6: '全自费',
        medical7: '其他社会保险',
        medical8: '贫困救助'
      },
      chartData: {
        queryDate: [], // 查询日期备份
        querytype: '', // 查询下拉备份
        titleText: '无数据', // 图表数据
        legendData: [], // 图表数据
        type: '', // big small
        data: [] // 图表数据
      },
      queryConditionBackup: {} // 查询数据备份
      // diagnoseList: {
      //   'siemidia': 'STEMI',
      //   'nstemidia': 'NSTEM',
      //   'uadia': 'UA',
      //   'aorticdissection': '主动脉夹层',
      //   'pulmonary': '肺动脉检查',
      //   'Non-ACS_cardiogenic_chest_pain': '非ACS心源性胸痛',
      //   'othercardiogeni': '其他非心源性胸痛'
      // }
    }
  },

  computed: {},
  created() {},
  mounted() {
    this.queryEchart()
  },
  methods: {
    /*
      *根据echart图数据查询表格
    */
    queryList() {
      this.queryConditionBackup.type = this.queryConditionBackup.type || ''
      this.monthTableData = []
      this.queryConditionBackup.pageNum = undefined
      this.queryConditionBackup.pageSize = undefined
      statisticsQueryMonth(this.queryConditionBackup).then(res => {
        this.monthTableData = res.data
        this.tableLoading = false
      })
    },
    monthDetails(row = {}) {
      this.tableData = []
      this.recoverParams()
      this.queryConditionBackup.month = row.month
      this.queryDetailsTable()
    },
    queryDetailsTable() {
      const params = {
        querytype: this.queryConditionBackup.querytype,
        startTime: this.queryConditionBackup.month,
        endTime: this.queryConditionBackup.month,
        type: this.queryConditionBackup.type,
        hospitalId: this.queryConditionBackup.hospitalId,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }
      statisticsQueryInfo(params).then(res => {
        this.tableData = res.data
        this.count = res.count
        this.tableLoading = false
      })
    },

    /*
      *重置分页信息
    */
    recoverParams() {
      this.pageNum = 1
      this.pageSize = 10
      this.count = 0
    },
    /*
      * 查询echart图数据
    */
    queryEchart() {
      if (this.queryData.queryDate.length == 0 || this.queryData.queryDate.length < 2) {
        this.$message.warning('时间范围不能为空')
        return false
      }
      if (!this.queryData.querytype) {
        this.$message.warning('统计质控不能为空')
        return false
      }
      this.recoverParams()
      this.tableData = []
      this.monthTableData = []
      this.chartData = {
        queryDate: [], // 查询日期备份
        querytype: '', // 查询下拉备份
        titleText: '无数据', // 图表数据
        legendData: [], // 图表数据
        data: [], // 图表数据
        titleX: [] // x轴数据
      }
      this.chartData.titleText = this.optionData[this.queryData.querytype]

      const params = {
        querytype: this.queryData.querytype,
        hospitalId: this.$store.getters.hospitalId
      }
      if (!!this.queryData.queryDate && this.queryData.queryDate.length === 2) {
        if (this.queryData.queryDate[0] instanceof Date) {
          params.startTime = this.queryData.queryDate[0].getFullYear() + '-' + (this.queryData.queryDate[0].getMonth() + 1)
          params.endTime = this.queryData.queryDate[1].getFullYear() + '-' + (this.queryData.queryDate[1].getMonth() + 1)
        } else {
          params.startTime = this.queryData.queryDate[0]
          params.endTime = this.queryData.queryDate[1]
        }
      }
      statisticsQuery(params).then(res => {
        this.queryConditionBackup = params
        if (this.queryData.querytype !== 'stroke2') {
          this.pie_or_line = 'pie'
          this.tableCol = 14
          this.chartData.data = []
          this.chartData.legendData = []
          console.log(res)
          for (const index in res.data) {
            if (index !== 'sum') {
              this.chartData.data.push({
                value: res.data[index], name: this.pieDataName[index], type: index
              })
              this.chartData.legendData.push(this.pieDataName[index])
            }
          }
          // res.data.forEach((item, index) => {
          //   this.chartData.data.push({
          //     value: item, name: this.pieDataName[index], type: ''
          //   })
          //   this.chartData.legendData.push(item)
          // })
          this.$nextTick(() => {
            this.echartPie()
          })
        } else {
          this.pie_or_line = 'line'
          this.tableCol = 24
          this.chartData.titleX = []
          this.chartData.data = []
          res.data.forEach(item => {
            this.chartData.titleX.push(item.created_at)
            this.chartData.data.push({
              value: item.time, name: item.name || '患者未命名'
            })
            // this.chartData.data.push(item.time)
          })
          this.$nextTick(() => {
            this.echartLine(res)
          })
        }
      })
    },
    handleSizeChange(val) {
      this.queryDetailsTable()
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.queryDetailsTable()
      console.log(`当前页: ${val}`)
    },
    /*
      *  生成echart图
    */
    echartLine(res) {
      const option = {
        title: {
          text: this.chartData.titleText
        },
        tooltip: {
          trigger: 'axis',
          // formatter: '{a} <br/>{b}: {c} ({d}%)'
          formatter: '患者: {b} <br/>{c}  (日)'
        },
        legend: {
          // data: ['销量']
        },
        xAxis: {
          data: this.chartData.titleX
        },
        yAxis: {},
        dataZoom: [{
          type: 'inside'
        }],
        series: [{
          name: '',
          type: 'line',
          data: this.chartData.data
        }]
      }
      const chartLine = this.$refs.chartLine
      if (chartLine) {
        const myChart = echarts.init(chartLine)
        myChart.setOption(option)
        this.queryList()
        // this.tableData = res.data
        // this.count = res.count

        // myChart.off('click') // 解除click！解决重复点击
        // myChart.on('click', (params) => {
        //   this.recoverParams()
        //   this.queryList(params.data)
        //   // statisticsQueryInfo
        //   console.log(params)
        // })
      }
    },
    /*
      *  生成echart图
    */
    echartPie() {
      const option = {
        title: {
          text: this.chartData.titleText,
          // subtext: '副标题',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          // formatter: '{a} <br/>{b}: {c} ({d}%)'
          formatter: '{b} <br/>{c}  占比({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          top: 30,
          data: this.chartData.legendData
        },
        series: [
          {
            name: '',
            type: 'pie',
            top: 50,
            radius: ['0%', '80%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'inner'
            },
            // emphasis: {
            //   label: {
            //     show: true,
            //     fontSize: '15',
            //     fontWeight: 'bold'
            //   }
            // },
            // labelLine: {
            //   show: true
            // },
            data: this.chartData.data
          }
        ]
      }
      const chart = this.$refs.chart
      if (chart) {
        const myChart = echarts.init(chart)
        myChart.off('click') // 解除click！解决重复点击
        myChart.setOption(option)
        myChart.on('click', (params) => {
          this.recoverParams()
          this.tableData = []
          this.monthTableData = []
          this.tableLoading = true
          this.queryConditionBackup.type = params.data.type
          this.queryList()
          // console.log(params)
        })
      }
    },
    /* 跳转查看*/
    jumpsee(row) {
      row.sourcePage = 'strokeStatistical.vue'
      row.greenType = '卒中'
      this.$router.push({
        name: 'patientsList',
        params: row
      })
    },
    /*
      *重置查询条件
    */
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }

  }
}
</script>

<style>
  .dividerLine{
    position: relative;
    top: -20px;
  }
  .echarts-dom{
    width: 100%;
    height: 500px;
  }
  .pointerEvents{
    pointer-events:none
  }
</style>
